package com.ruoyi.project.system.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SmCustomizedPrice;
import com.ruoyi.project.system.domain.SmProduct;
import com.ruoyi.project.system.domain.vo.ProductVo;
import com.ruoyi.project.system.mapper.SmCustomizedPriceMapper;
import com.ruoyi.project.system.mapper.SmProductMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISmProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/product")
public class SmProductController extends BaseController {

    @Autowired
    private ISmProductService smProductService;

    @Autowired
    private SmProductMapper smProductMapper;

    @Autowired
    private SmCustomizedPriceMapper smCustomizedPriceMapper;

    @Autowired
    private SysUserMapper userMapper;

    @GetMapping("/posterImg")
    public Object posterImg(@NotBlank String code) {
        return smProductMapper.allImg(code);
    }

    @GetMapping("/addImg")
    public AjaxResult addImg(@NotBlank String code, @NotBlank String url) {
        return toAjax(smProductMapper.addImg(code, url));
    }

    @GetMapping("/setImg")
    public AjaxResult setImg(@NotNull Integer id, @NotBlank String status) {
        return toAjax(smProductMapper.updateImg(id, status));
    }

    @GetMapping("/deleteImg")
    public AjaxResult deleteImg(@NotNull Integer id) {
        return toAjax(smProductMapper.deleteImg(id));
    }

    /**
     * 客户端产品详情页
     *
     * @param productId
     * @return
     */
    @GetMapping("/baseInfo")
    public AjaxResult baseInfo(@NotNull Integer productId) {
        Long userId = SecurityUtils.getUserId();
        SmProduct smProduct = smProductService.selectSmProductById(productId);
        ProductVo productVo = new ProductVo(smProduct);
        Integer roleId = userMapper.queryRoleId(userId);
        BigDecimal basePrice = smProductService.userBasePrice(userId, roleId, smProduct);
        BigDecimal promotionAdd = smProductService.promotionAdd(userId, smProduct);
//        BigDecimal fr = getChouRui(basePrice.add(promotionAdd));
        productVo.setBasePricing(basePrice);
        productVo.setPromotionAdd(promotionAdd);
        productVo.setBasePriceAdd(smProductService.basePriceAdd(userId, smProduct));
        productVo.setMaxBasePriceAdd(smProductService.maxLimit(userId, smProduct, roleId + "-MAX-XJTC"));
        productVo.setMaxPromotionAdd(smProductService.maxLimit(userId, smProduct, roleId + "-MAX-TGSY"));
        return success(productVo);
    }

    /**
     * 查询某用户所有在展产品基础信息，底价（自用价），推广收益
     */
    @GetMapping("/promotion")
    public AjaxResult promotion() {
        return success(smProductService.promotion());
    }

    @Anonymous
    @GetMapping("/promotionPrice")
    public BigDecimal promotionPrice(@NotNull Long userId, @NotNull Integer productId) {
        return smProductService.promotionPrice(
                userId,
                userMapper.queryRoleId(userId),
                smProductMapper.selectSmProductById(productId)
        );
    }

    @GetMapping("/setPrice")
    public AjaxResult setPrice(SmCustomizedPrice customizedPrice) {
        Long userId;
        if (customizedPrice.getUserId() == null) {
            userId = SecurityUtils.getUserId();
        } else {
            userId = customizedPrice.getUserId().longValue();
        }
        SmProduct smProduct = smProductService.selectSmProductById(customizedPrice.getProductId());
        Integer roleId = userMapper.queryRoleId(userId);
        if ("XJTC".equals(customizedPrice.getType())) {
            if (customizedPrice.getAmount().compareTo(smProductService.maxLimit(userId, smProduct, roleId + "-MAX-XJTC")) > 0) {
                return error("下级提成应小于最大下级提成！");
            }
        } else if ("TGSY".equals(customizedPrice.getType())) {
            if (customizedPrice.getAmount().compareTo(smProductService.maxLimit(userId, smProduct, roleId + "-MAX-TGSY")) > 0) {
                return error();
            }
        } else {
            customizedPrice.setType(roleId + "-" + customizedPrice.getType());
        }
        customizedPrice.setUserId(userId.intValue());
        SmCustomizedPrice smCustomizedPrice = smCustomizedPriceMapper.selectSmCustomizedPrice(customizedPrice);
        if (smCustomizedPrice == null) {
            customizedPrice.setCreateBy(SecurityUtils.getUsername());
            return toAjax(smCustomizedPriceMapper.insertSmCustomizedPrice(customizedPrice));
        } else {
            customizedPrice.setId(smCustomizedPrice.getId());
            customizedPrice.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(smCustomizedPriceMapper.updateSmCustomizedPrice(customizedPrice));
        }
    }

    /**
     * 自查需求参数
     */
    @GetMapping("/selfQuery")
    public AjaxResult selfQuery(@NotNull Integer productId) {
        AjaxResult result = new AjaxResult();
        SmProduct smProduct = smProductMapper.selectSmProductById(productId);
        result.put("name", smProduct.getName());
        result.put("status", smProduct.getStatus());
        result.put("remark", smProduct.getRemark());

        Long userId = SecurityUtils.getUserId();
        Integer roleId = userMapper.queryRoleId(userId);
        result.put("price", smProductService.userBasePrice(userId, roleId, smProduct));
        return result;
    }

    /**
     * 首页产品
     */
    @Anonymous
    @GetMapping("/home")
    public AjaxResult homeList() {
        AjaxResult result = new AjaxResult();
        List<Map<String, String>> PRO = smProductMapper.homePageProducts("1");
        result.put("PRO", PRO);
        result.put("more", smProductMapper.productCount() > PRO.size());
        return result;
    }

    @GetMapping("/noHome")
    public AjaxResult noHomeProducts() {
        return success(smProductMapper.homePageProducts(""));
    }

    @GetMapping("/img")
    public AjaxResult img(@NotBlank String code) {
        AjaxResult result = new AjaxResult();
        result.put("urls", smProductMapper.img(code));
        result.put("ic", smProductService.inviteCode(
                SecurityUtils.getUserId(),
                code
        ));
        return result;
    }

    @GetMapping("/distinct")
    public AjaxResult distinct() {
        Long userId = SecurityUtils.getUserId();
        AjaxResult result = new AjaxResult();
        result.put("product", smProductMapper.distinctProductName());
        result.put("nick", userMapper.distinctNickName(userId));
        return result;
    }

    /**
     * 获取产品状态
     */
    @Anonymous
    @GetMapping("/status")
    public AjaxResult status(@NotNull Integer productId) {
        Map result = new HashMap();
        SmProduct smProduct = smProductMapper.selectSmProductById(productId);
        result.put("status", smProduct.getStatus());
        result.put("remark", smProduct.getRemark());
        result.put("code", smProduct.getCode());
        return success(result);
    }

    /**
     * 查询产品列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/list")
    public AjaxResult list() {
        return success(smProductMapper.selectSmProductList_());
    }

    /**
     * 获取产品详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(smProductService.selectSmProductById(id));
    }

    /**
     * 修改产品
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SmProduct smProduct) {
        return toAjax(smProductService.updateSmProduct(smProduct));
    }
}
